using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CodRevit.ViewModels;
using CodRevit.Views;

namespace CodRevit.Commands
{
    [Transaction(TransactionMode.Manual)]
    public class ScatterFamilyCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // 创建ExternalEvent和Handler
            // ScatterFamilyHandler派生自IExternalEventHandler
            var scatterHandler = new ScatterFamilyHandler(commandData.Application.ActiveUIDocument.Document);
            var externalEvent = ExternalEvent.Create(scatterHandler);
            // 创建View和ViewModel
            var window = new ScatterFamilyView();
            //ViewModel构造函数出入View是因为用户选择构件时候需要临时隐藏窗口
            //传入scatterHandler实例是为了将前台绑定在vm中的数据设置到handler中
            //传入externalEvent是为了调用外部事件的raise方法
            var viewModel = new ScatterFamilyViewModel(
                commandData.Application,
                window,
                externalEvent,
                scatterHandler);
            window.DataContext = viewModel;

            // 将窗口放置到Revit建模空间的左上角
            var positionedWindow = App.LeftTopWindow(commandData, window);
            if (positionedWindow == null || positionedWindow is not Views.ScatterFamilyView)
            {
                return Result.Failed;
            }
            window = (Views.ScatterFamilyView)positionedWindow;
            window.Show();
            return Result.Succeeded;
        }
    }
}